package cn.itcast.web;

import cn.itcast.mapper.accountMapper;
import cn.itcast.mapper.userMapper;
import cn.itcast.pojo.account;
import cn.itcast.pojo.accountExample;
import cn.itcast.pojo.user;
import cn.itcast.util.OutputStringController;
import cn.itcast.util.WechatUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 欧阳辉
 * @desc
 * @email 634272623@qq.com
 */

@Slf4j
@RestController
@RequestMapping(value="/wxshop/user",produces="text/html;charset=UTF-8")
public class loginController {

    @Resource
    private cn.itcast.mapper.userMapper userMapper;

    @Resource
    cn.itcast.mapper.accountMapper accountMapper;
    @Resource
    OutputStringController osc;

    /**
     * 微信用户登录详情
     */
    @PostMapping("login")
    @ResponseBody
    public String user_login(@RequestParam(value = "code", required = false) String code,
                                   @RequestParam(value = "rawData", required = false) String rawData,
                                   @RequestParam(value = "signature", required = false) String signature,
                                   @RequestParam(value = "encrypteData", required = false) String encrypteData,
                                   @RequestParam(value = "iv", required = false) String iv) {
        // 用户非敏感信息：rawData
        // 签名：signature
        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenIdToUser(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");
        log.debug(sessionKey);
        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        if (!signature.equals(signature2)) {
            return osc.resultFailure( "签名校验失败", null);
        }
        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
        user user = this.userMapper.selectByPrimaryKey(openid);
        // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
        String skey = UUID.randomUUID().toString();
        Map<String,String> map = new HashMap<>();
        map.put("openId",openid);
        map.put("skey",skey);
        String result ="";
        if (user == null) {
            // 用户信息入库
            String nickName = rawDataJson.getString("nickName");
            String avatarUrl = rawDataJson.getString("avatarUrl");
            String gender = rawDataJson.getString("gender");
            String city = rawDataJson.getString("city");
            String country = rawDataJson.getString("country");
            String province = rawDataJson.getString("province");

            user = new user();
            user.setOpenId(openid);
            user.setSkey(skey);
            user.setCreateTime(new Date());
            user.setLastVisitTime(new Date());
            user.setSessionKey(sessionKey);
            user.setCity(city);
            user.setProvince(province);
            user.setCountry(country);
            user.setAvatarUrl(avatarUrl);
            user.setGender((byte) Integer.parseInt(gender));
            user.setNickName(nickName);
            user.setCreates(new Date().getTime());       //获取13位时间戳
            user.setLastVisit(new Date().getTime());    //获取13位最后登录时间戳

            account account = new account();
            account.setOpenId(openid);
            account.setAccountName(rawDataJson.getString("nickName"));
            account.setAccountTypeid(2);
            account.setAccountNumber("0101");

            //创建用户账户
            accountExample aEx = new accountExample();
            accountExample.Criteria criteria = aEx.createCriteria();
            criteria.andOpenIdEqualTo(account.getOpenId());
            List<cn.itcast.pojo.account> accounts = accountMapper.selectByExample(aEx);
            if(accounts.isEmpty()){
                int i = accountMapper.insertSelective(account);
                if(i==1){
                    result =osc.resultSuccess("登录成功",map);
                }else{
                    result =osc.resultFailure("登录成功，账户创建失败",map);
                }
            }

            userMapper.insert(user);
        } else {
            String nickName = rawDataJson.getString("nickName");
            String avatarUrl = rawDataJson.getString("avatarUrl");
            // 已存在，更新用户登录时间
            user.setLastVisitTime(new Date());
            user.setLastVisit(new Date().getTime());
            user.setNickName(nickName);
            user.setAvatarUrl(avatarUrl);
            user.setSessionKey(sessionKey);
            // 重新设置会话skey
            user.setSkey(skey);
            this.userMapper.updateByPrimaryKeySelective(user);
            result = osc.resultSuccess("登录成功,更新登录时间",map);
    }
        //encrypteData比rowData多了appid和openid
        //JSONObject userInfo = WechatUtil.getUserInfo(encrypteData, sessionKey, iv);
        //6. 把新的skey返回给小程序

        return result;
    }



}